<template>
    <div>
        <div>
            <el-button class="btn"
                type="default"
                @click="openHandle"><i class="iconfont icon-shangchuan icon-upload"></i>{{btnText}}</el-button>
            <span class="tip">{{tip}}</span>
        </div>
        <!-- 上传附件 -->
        <!-- <file-item isImg :fileList="uploadFileList" @update-file="updateFile"></file-item> -->
        <!-- 素材库 -->
        <material v-model:value="addVisible"
            :subCategory="data.subCategory"
            :list-type="1"
            :category="data.fileTypes"
            :limit="limitLength"
            :limitSize="fileSize"
            @on-ok="fileInsert" />
    </div>
</template>

<script setup>
// import FileItem from './file-item.vue';
import Material from '@/components/material/index.vue';
import { ref, reactive, computed, onMounted, watch, defineEmits, defineProps} from 'vue'
import { sizeFormat } from '@/lib/tools.js';

const emit = defineEmits(['update:fileList']);

const props = defineProps({
    checkConfig: { // 文件校验要求，来自模板
        type: Object,
        default: () => {
            return {}
        }
    },
    fileList: { // 文件
        type: Array,
        default: () => {
            return [];
        }
    },
    btnText: {
        type: String,
        default: '选择图片'
    }
})

// 素材库是否显示
const addVisible = ref(false);

const uploadFileList = ref([]); // 上传的文件

const data = reactive({
    fileTypes: ['all', 'document', 'audio', 'video', 'img', 'other'],
    subCategory: ['jpg', 'jpeg', 'png']
})


watch(() => props.fileList, (val) => {
    uploadFileList.value = Object.assign([], val);
}, {deep: true})

onMounted(() => {
    uploadFileList.value = Object.assign([], props.fileList || []);
})

// 校验规则
const rules = computed(() => {
    if(props.checkConfig.checkType === 'multifile') { // 多个
        const arr = props.checkConfig.checkRuleDTOS || [];
        let temp = {};
        arr.length > 0 && arr.forEach(item => {
            if (item.checkType === 'length') {
                temp.limitLength = Number(item.checkValue);
            } else if (item.checkType === 'fileTypes') {
                temp[item.checkType] = item.checkValue.split(',');
            } else {
                temp[item.checkType] = item.checkValue;
            }
        })
        return temp;
    } else if (props.checkConfig.checkType === 'fileSize') { // 文件大小
        return { fileSize: props.checkConfig.checkValue };
    } else if (props.checkConfig.checkType === 'length') { // 长度
        return { limitLength: Number(props.checkConfig.checkValue) };
    } else {
        return {};
    }
})

// 最多上传多少个文件
const limitLength = computed(() => {
    let maxLimit = rules.value && rules.value.limitLength || 9;
    return maxLimit - uploadFileList.value.length;
});

// 上传最大容量
const fileSize = computed(() => { // 规定后台返回的单位是M,素材库是byte，默认1M
    return rules.value && rules.value.fileSize && Number(rules.value.fileSize) * 1024 * 1024 || 1 * 1024 * 1024;
});

const tip = computed(() => {
    if (props.checkConfig.tips) {
        return props.checkConfig.tips;
    } else {
        let type = rules.value && rules.value.fileTypes && rules.value.fileTypes.join('，');
        let size = sizeFormat(fileSize.value);
        let content = type && `支持格式：${type}；` || '';
        return `${content}大小不能超过${size}`
    }
});



// 已经选择的文件
// const checkedFileList = computed(() => {
//     let file = uploadFileList.value.map(item=>item.materialId);
//     return file.length && JSON.parse(JSON.stringify(file)) || [];
// });

// 打开素材库
function openHandle() {
    data.fileTypes = ['img'];
    data.subCategory = rules.value && rules.value.fileTypes || ['jpg', 'jpeg', 'png'];
    addVisible.value = true;
    
}

// 选择文件
function fileInsert(fileList) {
    if (!fileList[0]) {
        return;
    }
    fileList.forEach(item => {
        // let fileIndex = uploadFileList.value.findIndex(file => file.materialId === item.materialId);
        // if(fileIndex === -1){
        //    uploadFileList.value.push(item);
        // }
        uploadFileList.value.push(item);
    })
    console.log(uploadFileList.value);
    emit('update:fileList', uploadFileList.value);
}

// 修改文件
function updateFile(val){
    uploadFileList.value = JSON.parse(JSON.stringify(val));
    emit('update:fileList', val);
}


</script>

<style lang="scss" scoped>
.upload-file {
    width: 100px;
    display: inline-block;
}
.btn {
    min-height:30px !important;
    padding: 8px 12px;
    border-radius: 2px;
    border: 1px solid var(--color-primary);
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: var(--color-primary);
    line-height: 14px;
    .icon-upload{
        margin-right:4px;
        display: inline-block;
        font-size:14px;
    }
}
.tip{
    height: 17px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: var( --main-text-tip);
    line-height: 17px;
    display: inline-block;
    margin-left:8px;
}
</style>